from urllib import request,parse
import json,requests

def youdao_urllib(kw):
	url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
	data = {
	'i': kw,
	'from': 'AUTO',
	'to': 'AUTO',
	'doctype': 'json',
		}
	data = parse.urlencode(data)

	headers = {
	'Content-Length':len(data),
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',
		}

	req = request.Request(url,data = bytes(data,encoding = 'utf-8'),headers = headers)
	res = request.urlopen(req)

	str_json = res.read().decode('utf-8')
	myjson = json.loads(str_json)
	print('Result:' + myjson['translateResult'][0][0]['tgt'])

def youdao_requests(kw):
	url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
	data = {
	'i': kw,
	'from': 'AUTO',
	'to': 'AUTO',
	'doctype': 'json',
		}
	res = requests.post(url,data = data)
	
	str_json = res.content.decode('utf-8')
	myjson = json.loads(str_json)
	print('Result:' + myjson['translateResult'][0][0]['tgt'])

if __name__ == '__main__':
	while True:
		print("Please input the method")
		method = int(input("1.urllib    2.requests  other.quit\n"))
		if method == 1:
			kw = input("Please input the word: ")
			youdao_urllib(kw)
		elif method == 2:
			kw = input("Please input the word: ")
			youdao_requests(kw)
		else:
			break
